package com.atguigu.gmall.pms.service.impl;

import com.agtuigu.gmall.pms.vo.CategoryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.core.bean.PageVo;
import com.atguigu.core.bean.Query;
import com.atguigu.core.bean.QueryCondition;

import com.atguigu.gmall.pms.dao.CategoryDao;
import com.agtuigu.gmall.pms.entity.CategoryEntity;
import com.atguigu.gmall.pms.service.CategoryService;

import java.util.List;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageVo queryPage(QueryCondition params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageVo(page);
    }

    @Override
    public List<CategoryVo> querySubCategories(Long pid) {
            //1.根据id查询一级分类下的二级分类
            QueryWrapper<CategoryEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("parent_cid", pid);
            //1.2拿到二级分类数据
            List<CategoryEntity> categoryEntities = this.list(wrapper);
            //通过stream表达式将List<CategoryEntity>转换成CategoryVo
            List<CategoryVo> categoryVos = categoryEntities.stream().map(categoryEntity -> {
                CategoryVo categoryVo = new CategoryVo();
                //BeanUtils.copyProperties(源对象,目标对象) 快速赋值
                BeanUtils.copyProperties(categoryEntity, categoryVo);
                //再根据二级分类的id查询二级分类下的三级分类
                QueryWrapper<CategoryEntity> categoryEntityQueryWrapper = new QueryWrapper<>();
                //根据二级分类id查询三级分类
                categoryEntityQueryWrapper.eq("parent_cid", categoryEntity.getCatId());
                List<CategoryEntity> list = this.list(categoryEntityQueryWrapper);
                categoryVo.setSubs(list);
                return categoryVo;
            }).collect(Collectors.toList());

            return categoryVos;

        }


}